package com.zhongxi.guoyuan.fragment.RewardCoinOrder;


import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.rewardCoinOrder.RewardOrderHasNoTokenAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.rewardcoin.MallInfoResult;
import com.zhongxi.guoyuan.entity.rewardcoin.RewardCoinOrderResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.MyTextUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class RewardOrderHasNoTokenFragment extends BaseFragment implements AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener2<ListView> {

    private PullToRefreshListView lvList;
    private RewardOrderHasNoTokenAdapter adapter;
    private List<RewardCoinOrderResult.RewardCoinOrder> data = new ArrayList<>();
    private String type;

    private int pos;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    //确认收货
                    pos = (int)msg.obj;
                    toSure((int)msg.obj);
                    break;
                case 1:
                    //我要投诉
                    showDialog((int)msg.obj);
                    break;
            }
        }
    };
    private String star;

    /**
     * 投诉弹窗
     */
    private void showDialog(final int pos) {
        try {
            View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_complain, null);
            final Dialog dialog = new AlertDialog.Builder(context).create();
            dialog.show();
            dialog.getWindow().setContentView(view);

            dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
            dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

            ImageView ivCancel = (ImageView) view.findViewById(R.id.ivCancel);
            final EditText etTips = (EditText) view.findViewById(R.id.etTips);
            final TextView tvNum = (TextView) view.findViewById(R.id.tvNum);
            Button btSubmit = (Button) view.findViewById(R.id.btSubmit);
            ivCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            etTips.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable content) {
                    MyTextUtils.TextChangeUtils(context, tvNum, content);
                }
            });

            /**
             * 投诉
             */
            btSubmit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String content = etTips.getText().toString().trim();
                    if(null!=content&&!"".equals(content)){
                        dialog.dismiss();
                        toComplaint(content, pos);
                    }else{
                        showShortToast("请输入投诉内容!");
                    }
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private Map<String, String> map = new HashMap<>();

    /**
     * 投诉
     */
    private void toComplaint(String content, int pos){
        type = "complaint";
        map.clear();
        map.put("orderid", data.get(pos).getOrderid());
        map.put("type", "1");
        map.put("content", content);
        getServer(Url.REWARD_TOCOMPLAIN, map, "", false, null, "post");
    }

    /**
     * 确认收货
     * @param pos
     */
    private void toSure(int pos) {
        type = "sure";
        map.clear();
        map.put("orderid", data.get(pos).getOrderid());
        map.put("type", "1");
        getServer(Url.REWARD_TOCONFIRM, map, "", false, null, "post");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_order_has_no_apply, container, false);
    }

    @Override
    protected void initView() {
        super.initView();
        lvList = (PullToRefreshListView) getView().findViewById(R.id.lvList);
    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new RewardOrderHasNoTokenAdapter(context, data, handler);
        lvList.setAdapter(adapter);
        getMall();
    }

    /**
     * 获取返银商城控制台信息
     */
    private void getMall() {
        type = "mall";
        getServer(Url.MALL_INFO, null, "", false, null, "get");
    }

    /**
     *  获取待自提订单
     */
    private void getOrder() {
        type = "order";
        String str = "&ordertype=1";
        getServer(Url.REWARD_TORECEIPT, null, str, false, null, "get");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            if("mall".equals(type)){
                MallInfoResult result = gson.fromJson(response, MallInfoResult.class);
                if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                adapter.setMall(result);
                getOrder();
            }else if("order".equals(type)) {
                RewardCoinOrderResult result = gson.fromJson(response, RewardCoinOrderResult.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                JSONObject obj = new JSONObject(response);
                JSONArray info = obj.getJSONArray("data");

                result.setInfo(info);

                lvList.onRefreshComplete();
                data.clear();
                if (result.getData().size() > 0) {
                    data.addAll(result.getData());
                }
                adapter.notifyDataSetChanged();
            }else if("sure".equals(type)){
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                showShortToast("确认订单成功，请给出您的评价！");
                showCommentWindow();
            }else if("complaint".equals(type)){
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                showShortToast("投诉成功！");
                getOrder();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try{
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            if(1000==result.getCode()){
                showShortToast("商品正在运输中");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 评论弹窗
     */
    private void showCommentWindow() {
        View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_reward_comment, null);
        final Dialog dialog = new AlertDialog.Builder(context).create();
        dialog.show();
        dialog.getWindow().setContentView(view);
        final ImageView ivCancel = (ImageView) view.findViewById(R.id.ivCancel);
        final TextView tvScore = (TextView) view.findViewById(R.id.tvScore);
        final TextView tvNum = (TextView) view.findViewById(R.id.tvNum);
        final EditText etTips = (EditText) view.findViewById(R.id.etTips);
        Button btSubmit = (Button) view.findViewById(R.id.btSubmit);
        RatingBar rb = (RatingBar) view.findViewById(R.id.rb);

        //评论
        btSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(TextUtils.isEmpty(etTips.getText().toString().trim())){
                    showShortToast("请输入评论内容！");
                }else{
                    toComment(etTips.getText().toString().trim());
                    dialog.dismiss();
                }
            }
        });

        //取消
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                getOrder();
            }
        });

        /**
         * 监听RatingBar的变化
         */
        rb.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener()
        {

            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                star = rating+"";
                tvScore.setText(rating+"");
            }
        });

        /**
         * 监听EditText输入字数
         */
        etTips.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable content) {
                MyTextUtils.TextChangeUtils(context, tvNum, content);
            }
        });

        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    }

    /**
     * 评论
     * @param comment
     */
    private void toComment(String comment) {
        try {
            type = "comment";
            map.clear();
            map.put("gid", data.get(pos).getGoodsId().get(0));
            map.put("starlevel", star);
            map.put("msg", comment);
            getServer(Url.REWARD_COMMENT, map, "", false, null, "post");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        lvList.setOnItemClickListener(this);
        lvList.setOnRefreshListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position-1 == adapter.getmExpandedMenuPos()) {
            adapter.setmExpandedMenuPos(-1);
        } else {
            adapter.setmExpandedMenuPos(position-1);
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        getOrder();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
    }
}
